package org.lcc.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.lcc.Service.CertificateService;
import org.lcc.model.VO.CertificateVO;
import org.lcc.mapper.CertificateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 证书服务实现类
 */
@Service
@Slf4j
public class CertificateServiceImpl implements CertificateService {

    @Autowired
    private CertificateMapper certificateMapper;
    
    /**
     * 证书存储路径
     */
    private final Path certificatesPath = Paths.get("certificates");
    
    @Override
    public Resource getCertificatePdf(String certificateCode) {
        try {
            Path filePath = certificatesPath.resolve(certificateCode + ".pdf");
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                throw new RuntimeException("无法读取证书文件: " + certificateCode);
            }
        } catch (Exception e) {
            throw new RuntimeException("获取证书文件失败: " + e.getMessage(), e);
        }
    }

    @Override
    public boolean verifyCertificate(String certificateCode) {
        try {
            // 查询证书状态
            return certificateMapper.selectById(certificateCode) != null;
        } catch (Exception e) {
            log.error("验证证书失败", e);
            return false;
        }
    }

    @Override
    public Map<String, Object> getStudentCertificates(String studentId, Integer pageNum, Integer pageSize, String keyword) {
        // 开启分页
        PageHelper.startPage(pageNum, pageSize);
        log.info("开始查询学生证书列表{}",studentId);
        // 执行查询
        List<CertificateVO> list = certificateMapper.selectStudentCertificates(studentId, keyword);
        log.info("查询结果{}",list);
        // 获取分页信息
        Page<CertificateVO> page = (Page<CertificateVO>) list;
        
        // 包装分页结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", page.getResult());
        result.put("total", page.getTotal());
        result.put("pages", page.getPages());
        result.put("pageNum", page.getPageNum());
        result.put("pageSize", page.getPageSize());
        
        return result;
    }


} 